/*
 * SortedColumnHeaderRenderer.java
 *
 * Created on 30. listopad 2006, 16:17
 *
 */

package cz.results.winter6.view.browse.table;

import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.LookAndFeel;
import javax.swing.SwingConstants;
import javax.swing.plaf.basic.BasicArrowButton;
import javax.swing.table.TableCellRenderer;

public class SortedColumnHeaderRenderer implements TableCellRenderer{
    
    protected TableCellRenderer textRenderer;
    protected SortedBrowseTableModel sortedModel;
    protected int sortCol=-1;
    protected boolean sortAscending=true;
    
    public SortedColumnHeaderRenderer(SortedBrowseTableModel sortedModel, TableCellRenderer textRenderer) {
        this.sortedModel = sortedModel;
        this.textRenderer = textRenderer;
    }
    
    public SortedColumnHeaderRenderer(SortedBrowseTableModel sortedModel){
        this(sortedModel,null);
    }
    
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col){
        Component text;
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        
        if(textRenderer!=null){
            text=textRenderer.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,col);
        } else {
            text = new JLabel((String)value,JLabel.CENTER);
            LookAndFeel.installColorsAndFont((JComponent)text,"TableHeader.background","TableHeader.foreground","TableHeader.font");
        }  
        
        panel.add(text,BorderLayout.CENTER);
        
        if(col==sortCol){
            BasicArrowButton bab = new BasicArrowButton((sortAscending ? SwingConstants.NORTH: SwingConstants.SOUTH));
            panel.add(bab,BorderLayout.WEST);
        }
        LookAndFeel.installBorder(panel,"TableHeader.cellBorder");
        return panel;
    }
    
    public void columnSelected(int col){
        if(col!=sortCol){
            sortCol=col;
            sortAscending=true;
        } else {
            sortAscending=!sortAscending;
            if(sortAscending) sortCol=-1;
        }
        if(sortCol!=-1){
            sortedModel.sortRows(sortCol, sortAscending);
        } else {
            sortedModel.clearSort();
        }
    }
}
